package com.zjr.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ModelDriven;
import com.zjr.domain.User;
import com.zjr.service.UserService;
import com.zjr.utils.Page;
import com.zjr.utils.UserUtil;
import com.zjr.utils.ViewUser;
/**
 * 用户Action类
 * */
public class UserAction extends SuperAction implements ModelDriven<User>{
	private static final long serialVersionUID = 1L;
	
	private User user = new User();
	@Override
	public User getModel() {
		return user;
	}
	
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	//用户登入
	public String login(){
		User existUser = userService.login(user);
		if(existUser != null){
			session.setAttribute("existUser", UserUtil.change(existUser));
			return "login_success";
		}else{
			request.setAttribute("errorMessage", "用户名或密码错误");
			return "login_failure";
		}
	}
	
	//用户添加
	public String save(){
		if(userService.save(user)){
			return "add_success";
		}else{
			return "add_failure";
		}
	}
	
	//查询所有用户的信息
	public String findAll(){
		List<ViewUser> list = userService.findAll();
		request.setAttribute("users", list);
		return "list";
	}
	
	//分页查询用户信息
	public String queryUser(){
		String pageCurrent = request.getParameter("pageCurrent");
		Page page = new Page();
		if(pageCurrent == null){
			page.setCurrentPage(1);
		}else{
			page.setCurrentPage(Integer.valueOf(pageCurrent));
		}
		List<ViewUser> list = userService.queryUser(page);
		request.setAttribute("users", list);
		request.setAttribute("page", page);
		return "list";
	}
	
	public String findById(){
		int uid = Integer.parseInt(request.getParameter("uid"));
		User user = userService.findById(uid);
		request.setAttribute("user", user);
		return "find";
	}
	
	public String modify(){
		userService.modify(user);
		return "modify";
	}
	
	public String delete(){
		int uid = Integer.parseInt(request.getParameter("uid"));
		userService.delete(uid);
		return "delete";
	}
	
	public String findByDid(){
		int did = Integer.parseInt(request.getParameter("did"));
		ArrayList<ViewUser> users = new ArrayList<ViewUser>();
		if(userService.findByDid(did) != null){
			for(User user : userService.findByDid(did)){
				users.add(UserUtil.change(user));
			}
			request.setAttribute("users", users);
			return "deaprtment_user";
		}else{
			return "no_user";
		}
		
	}
	
	public String findSelf(){
		int uid = Integer.parseInt(request.getParameter("uid"));
		User user = userService.findById(uid);
		request.setAttribute("self", user);
		return "self";
	}
}
